package JUC.第06章_内存模型之JMM;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class B2_指令重排 {

    @Test
    public void volatile_sort_demo() {
//        int x=11;   //1
//        int y=12;   //2
//        y+=x*x;      //3
//        x=x+5;      //4
//        //有可能1234     1243   21**
//        System.out.println(x+"       "+y);


        ReSortSeqDemo reSortSeqDemo=new ReSortSeqDemo();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                reSortSeqDemo.me2();
            },String.valueOf(i+1)).start();
            new Thread(()->{
                reSortSeqDemo.me1();
            },String.valueOf(i+1)).start();
        }
        while (Thread.activeCount() > 2){ Thread.yield();}//线程个数
    }//volatile  保证有序性
    @Test
    public void volatile_sort_demo2() {
//        int x=11;   //1
//        int y=12;   //2
//        y+=x*x;      //3
//        x=x+5;      //4
//        //有可能1234     1243   21**
//        System.out.println(x+"       "+y);


        ReSortSeqDemo reSortSeqDemo=new ReSortSeqDemo();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                reSortSeqDemo.sortDemo();
            },String.valueOf(i+1)).start();
        }
        while (Thread.activeCount() > 2){ Thread.yield();}//线程个数
    }//volatile  保证有序性

}
class ReSortSeqDemo{
    int a=0;
    //    AtomicInteger a=new AtomicInteger(0);//原子性的int
    boolean flag = false;
    public void sortDemo(){
        int x=11;
        int y=12;
        y+=x*x;
        x=x+5;
        System.out.println(y);
    }
    public void me1(){
//        a.compareAndSet(a.get(),1);
        a=1;
        flag=true;
    }
    public void me2(){
        if(flag){
            a+=5;
//            a.getAndAdd(5);
            if(a!=6){
                System.out.println(a);//在多线程下面   a可能等于11 也可能等于1 也可能输出6
            }
            flag = false;
        }
    }
}
